from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from subprocess import Popen
import subprocess
import os
import tempfile
import zipfile
import zipfile as package

tmpPath = tempfile.mkdtemp()
# packFile = raw_input("Select package: ")
packFile = "S:\Storage Service\AppSupport\Scripts\Python\Get-App\Source\Test Bay\Label.zip"
packFile = packFile.replace("\"", "")
pack = package.ZipFile(packFile, 'r')
print("     [*] Temporary Folder set to " + tmpPath)
print("     [*] Extracting \"" + packFile + "\"...")
for file in pack.namelist():
    pack.extract(file, tmpPath)



class Pack():
    sysArch = os.environ["PROCESSOR_ARCHITECTURE"]
    if sysArch == "x86":
        Bit = "32"
    else:
        Bit = "64"
    xml = ElementTree.parse(tmpPath + '\\Label.xml')
    Label = xml.findall('.')
    for Package in Label:
        Name = Package.attrib['name']
    xml = ElementTree.parse(tmpPath + '\\Label.xml')
    Package = xml.findall('Version')
    for Version in Package:
        for Arch in Version:
            for Stall in Arch:
                if Arch.attrib['bit'] == Bit:
                    if Stall.tag == "Install":
                        for Pre in Stall:
                            if Pre.tag == "Pre":
                                preInstallType = Pre.attrib['type']
                                preInstallText = Pre.text
                        for Post in Stall:
                            if Post.tag == "Post":
                                postInstallType = Post.attrib['type']
                                postInstallText = Post.text
                    else:
                        for Pre in Stall:
                            preUninstallType = Pre.attrib['type']
                            preUninstallText = Pre.text
                        for Post in Stall:
                            postUninstallType = Post.attrib['type']
                            postUninstallText = Post.text
    if preInstallType == "batch": extension = ".bat"
    preFile_ = 'preInstall' + Name + extension
    postFile_ = 'postInstall.' + Name + extension
    preFile = tmpPath + '\\' + preFile_
    postFile = tmpPath + '\\' + postFile_
    preInstallFile = open(preFile, 'w')
    print("     [*] Creating file " + preFile)
    preInstallFile.write(preInstallText)
    preInstallFile.close
    if postInstallType == "batch": extension = ".bat"
    postInstallFile = open(postFile, 'w')
    print("     [*] Creating file " + postFile)
    postInstallFile.write(postInstallText)
    postInstallFile.close
    print postFile_
    os.chdir(tmpPath)
    os.system(postFile_)


print Pack

